package com.yunshipei.core.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.yunshipei.core.common.RootCheck;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

@SuppressLint("HardwareIds")
public class SystemUtils {

    /**
     * 获取wifi的mac地址
     */
    public static String getMacAddress(Context context) {
        // 获取mac地址：
        String macAddress = "00:00:00:00:00:00";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                String address = wifiInfo.getMacAddress();
                if (!TextUtils.isEmpty(address)) {
                    macAddress = address;
                }
            }
        }
        return macAddress;
    }

    /**
     * 获取手机型号
     */
    public static String getDevicesName() {
        return Build.MANUFACTURER + "  " + Build.MODEL;
    }

    /**
     * 获取系统版本信息
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getApplicationContext().getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException ex) {
            ex.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取内核版本信息
     */
    public static String getKernelVersion() {
        Process process = null;
        String kernelVersion = "";
        try {
            process = Runtime.getRuntime().exec("cat/proc/version");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (process != null) {
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 8 * 1024);
            String result = "";
            String line;
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (!TextUtils.isEmpty(result)) {
                    String Keyword = "version ";
                    int index = result.indexOf(Keyword);
                    line = result.substring(index + Keyword.length());
                    index = line.indexOf(" ");
                    kernelVersion = line.substring(0, index);
                }
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
        return kernelVersion;
    }

    /**
     * 获取设备唯一标示的ID
     */
    public static String getDevicesID(Context context) {
        String devicesID = "";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = "";
        if (telephonyManager != null) {
            imei = telephonyManager.getDeviceId();
        }
        if (!TextUtils.isEmpty(imei)) {
            devicesID = imei;
        } else {
            String serialNum = getSerialNumber();
            if (!TextUtils.isEmpty(serialNum)) {
                devicesID = serialNum;
            } else {
                String androidID = getAndroidID(context);
                if (!TextUtils.isEmpty(androidID)) {
                    devicesID = androidID;
                }
            }
        }
        return devicesID;
    }

    /**
     * 获取Serial Number
     */
    private static String getSerialNumber() {
        String serialNum = "";
        try {
            @SuppressLint("PrivateApi") Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            serialNum = (String) (get.invoke(c, "ro.serialno", "unknown"));
        } catch (Exception ignored) {
        }
        return serialNum;
    }

    /**
     * 获取androidID
     */
    private static String getAndroidID(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    /**
     * 获取IMSI
     */
    public static String getSubscriberId(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            return telephonyManager.getSubscriberId();
        }
        return "undefine";
    }

    /**
     * 获取手机号
     */
    public static String getPhoneNumber(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            return telephonyManager.getLine1Number();
        }
        return "00000000000";
    }

    /**
     * 获取手机运营商
     */
    public static String getMobileOperator(Context context) {
        String subscriberId = getSubscriberId(context);
        if (subscriberId != null) {

            if (subscriberId.startsWith("46000") || subscriberId.startsWith("46002")) {
                return "中国移动";
            } else if (subscriberId.startsWith("46001")) {
                return "中国联通";
            } else if (subscriberId.startsWith("46003")) {
                return "中国电信";
            }
        }
        return "未安装sim卡";
    }

    /**
     * 判断手机是否root
     */
    public static boolean isDeviceRooted() {
        return new RootCheck().isDeviceRooted();
    }

    /**
     * 获取android版本
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取设备类型
     */
    public static String getPlatform(Context context) {
        return isPad(context) ? "tablet" : "phone";
    }

    /**
     * 判断是否为平板
     */
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取系统ISO格式的时间
     */
    public static String getISOTimeFormat() {
        TimeZone tz = SimpleDateFormat.getInstance().getTimeZone();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
        df.setTimeZone(tz);
        return df.format(new Date());
    }
}
